//
// Created by 11510 on 2024/6/13.
//
#include <iostream>
#include <pthread.h>
using namespace std;


class Singleton{
private:
    int _ix;
    int _iy;
    static Singleton * _pInstance;
    static pthread_once_t _once;

public:
    static Singleton * getInstance(){
        pthread_once(&_once, init_r);
        return _pInstance;
    }

    void init(int x,int y){
        _ix = x;
        _iy = y;
    }

    void print(){
        cout << "(" << this->_ix
             << "," << this->_iy
             << ")" << endl;
    }
private:
    static void init_r(){
        _pInstance = new Singleton(0, 0);
        atexit(destroy);
    }

    static void destroy(){
        if(_pInstance){
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    Singleton() = default;//C++11

    Singleton(int x,int y): _ix(x), _iy(y){
        cout << "Singleton(int,int)" << endl;
    }

    ~Singleton(){
        cout << "~Singleton()" << endl;
    }

    Singleton(const Singleton & rhs) = delete;
    Singleton & operator=(const Singleton & rhs) = delete;


};
Singleton * Singleton::_pInstance = nullptr;
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;



void test0(){
    Singleton::getInstance()->init(2, 9);
    Singleton::getInstance()->print();
//    此处不会double free

}

int main(void) {
    test0();
    return 0;
}
